package com.schoolegard.services.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.schoolegard.services.OrganizationService;
import com.schoolgard.dao.OrganizationDao;
import com.schoolgard.dao.SchoolDataDao;
import com.schoolgard.entitybean.AlarmLog;
import com.schoolgard.entitybean.GridDataModel;
import com.schoolgard.entitybean.Organization;
import com.schoolgard.entitybean.SchoolData;

public class OrganizationServiceImpl implements OrganizationService {
	
	private static Logger logger = Logger.getLogger(OrganizationServiceImpl.class);
	private OrganizationDao organizationDao;
	private SchoolDataDao schoolDataDao;
	public void setSchoolDataDao(SchoolDataDao schoolDataDao) {
		this.schoolDataDao = schoolDataDao;
	}
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}
	@Override
	public List<Organization> findByParentId(Long parentId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Organization.class);
		criteria.add(Restrictions.eq("_parentId", parentId));
		return organizationDao.findByCriteria(criteria);
	}
	@Override
	public Organization findById(Long id) {
		return organizationDao.findById(id);
	}
	@Override
	public List<Organization> findAll() {
		return organizationDao.findAll();	
	}
	@Override
	public List<Organization> findByRegions(Long regionsId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Organization.class);
		criteria.add(Restrictions.eq("regions.id", regionsId));
		return organizationDao.findByCriteria(criteria);
	}
	@Override
	public List<Organization> find_level_1_ByRegions(Long regionsId) {
		String hql1 = "select min(_parentId) from Organization where regions.id = "+regionsId;
		List parentIdObj = organizationDao.find(hql1);
		
		String hql = "from Organization where regions.id = "+regionsId +" and _parentId = "+parentIdObj.get(0);
		List<Organization> organizations = organizationDao.find(hql);
		return organizations;
	}
	@Override
	public void saveOrUpdate(Organization org) {
		organizationDao.createOrModify(org);
	}
	@Override
	public void delete(Long orgId) {
		organizationDao.remove(this.findById(orgId));
	}
	
	public GridDataModel<SchoolData> findSchoolPage(SchoolData schoolData,int first,int max) {
		DetachedCriteria criteria = DetachedCriteria.forClass(SchoolData.class);
		if(schoolData != null) {
			if(schoolData.getName() != null) {
				criteria.add(Restrictions.eq("name", schoolData.getName()));
			}
		}
		List<SchoolData> list = schoolDataDao.findByCriteria(criteria, first, max);
		int total = schoolDataDao.getRowCount(criteria);
		GridDataModel<SchoolData> page = new GridDataModel<SchoolData>();
		page.setPage(first / max + 1);
		page.setRows(list);
		page.setTotal(total);
		return page;
		
	}
}
